package com.yl.system.commer;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * Aa
 *
 * @author LeYang
 * on 2025/5/4
 */
public class Aa {
    public static void main(String[] args) throws IOException, InterruptedException {
        convertPngToSvg(new File("C:\\Users\\Administrator\\Desktop\\test\\下载.png"));
    }


    public static File convertPngToSvg(File pngFile) throws IOException, InterruptedException {
        // 1. 将 PNG 转成 PGM 灰度图格式（中间文件）
        BufferedImage image = ImageIO.read(pngFile);
        File pgmFile = new File("temp.pgm");
        writeImageAsPGM(image, pgmFile); // 自定义方法，见下方

        // 2. 调用 Potrace：pgm → svg
        File svgFile = new File("output.svg");
        ProcessBuilder pb = new ProcessBuilder("C:\\Users\\Administrator\\Desktop\\基础依赖\\potrace-1.16.win64\\potrace.exe", pgmFile.getAbsolutePath(), "-s", "-o", svgFile.getAbsolutePath());
        pb.redirectErrorStream(true);
        Process process = pb.start();
        process.waitFor();

        System.out.println("11111111111");
        return svgFile;
    }

    public static void writeImageAsPGM(BufferedImage image, File pgmFile) throws IOException {
        int width = image.getWidth();
        int height = image.getHeight();
        int threshold = 128; // 灰度转黑白的阈值

        try (FileOutputStream fos = new FileOutputStream(pgmFile);
             BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos))) {

            // 写 PGM 文件头
            bw.write("P2\n");
            bw.write(width + " " + height + "\n");
            bw.write("255\n");
            bw.flush();

            // 遍历像素
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int argb = image.getRGB(x, y);
                    int alpha = (argb >> 24) & 0xff;

                    if (alpha < 128) {
                        // 透明像素 ➜ 白色（背景）
                        bw.write("255 ");
                    } else {
                        int r = (argb >> 16) & 0xff;
                        int g = (argb >> 8) & 0xff;
                        int b = argb & 0xff;
                        int gray = (r + g + b) / 3;
                        int bwPixel = (gray < threshold) ? 0 : 255;
                        bw.write(bwPixel + " ");
                    }
                }
                bw.write("\n");
            }
        }
    }
}
